/*
 * @Author: VC
 * @Date: 2024-05-20 15:35:30
 */

class SubscribePublic {
    constructor() {
        this.eventBus = {}
    }

    /**
     * 事件订阅器
     * @param name String
     * @param fn Function
     */
    subscribe (name, fn) {
        if (name && typeof name === 'string' && fn instanceof Function) {
            if (this.eventBus.hasOwnProperty(name)) {
                try {
                    this.eventBus[name].push(fn)
                } catch (error) {
                    throw new Error(error)
                }
            } else {
                this.eventBus[name] = []
                this.eventBus[name].push(fn)
            }

        } else {
            throw new Error('参数错误: @param name String，@param fn Function')
        }
    }
    /**
     * 事件触发-执行阶段
     * @param name string
     * @param args any
     */
    run (name, args) {
        if (this.eventBus[name] instanceof Array) {
            for (let x of this.eventBus[name]) {
                x && x(args)
            }
        }
    }
    /**
     * 事件发布
     * @param name string
     * @param args any
     */
    public (name, ...args) {
        if (this.eventBus.hasOwnProperty(name)) {
            this.run(name, args)
        }
    }
    /**
     * 移除订阅
     * @param name string
     */
    unsubscribe (name) {
        delete this.eventBus[name]
    }

}
export default new SubscribePublic()
